How to get the sum for every distinct value in another column?
How to get the sum for every distinct value in another column?
445
27-Jul-2023
Updated on 28-Jul-2023
Aryan Kumar
28-Jul-2023Sure, you can get the sum for every distinct value in another column using the
GROUP BYclause and theSUM()function. The syntax is as follows:SQL
For example, if you have a table called
productswith the columnsnameandprice, you could use the following SQL statement to get the sum of all product prices for each unique product name:SQL
This would return a table with two columns:
nameandsum. Thenamecolumn would contain the unique product names, and thesumcolumn would contain the sum of all product prices for each unique product name.Here is an example of how to get the sum for every distinct value in another column in MySQL:
SQL
This will return the following result:
As you can see, the
GROUP BYclause has grouped the rows in theproductstable by thenamecolumn. TheSUM()function has then been used to calculate the sum of all product prices for each unique product name.